package com.simon.hse.http;

import android.text.TextUtils;
import android.util.Log;

import com.simon.hse.MyApplication;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Response;

/**
 * 创建一个保存Cookie的拦截器，用于获取服务器打给客户端的Cookie信息
 */
@SuppressWarnings("all")
public class WriteCookiesInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        //获取到响应
        Response originalResponse = chain.proceed(chain.request());
        //进行Cookie获取以及字符串的拼接，Cookie在使用的过程要根据具体公司来定

        StringBuffer stringBuffer = new StringBuffer();
        if (!originalResponse.headers("Set-Cookie").isEmpty()) {
            //根据Set-Cookie获取出的信息
            for (String header : originalResponse.headers("Set-Cookie")) {
                // Log.i("Simon", "header = " + header );
                String cookie = header.substring(0, header.indexOf(";") + 1);
                stringBuffer.append(cookie);
            }
        }
        //拼接时完成后将该Cookie保存到 SharedPreferences中
        if (!TextUtils.isEmpty(stringBuffer.toString())) {
            // Log.i("Simon", "Write Cookie = " + stringBuffer.toString());
            PreferencesCookie.putString(MyApplication.getInstance(), "cookie", stringBuffer.toString());
        }
        return originalResponse;
    }
}